package com.irssproject.app.web.action.main;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.irssproject.app.entitats.Label;
import com.irssproject.app.entitats.User;
import com.irssproject.app.service.lectorRSS.iface.SubscriptionsService;
import com.irssproject.app.service.main.iface.UsersService;
import com.irssproject.app.utils.Constants;
import com.irssproject.app.utils.Utils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@SuppressWarnings("rawtypes")
public class LoginAction extends ActionSupport implements SessionAware, ModelDriven {

    /**
     *
     */
    private static final long serialVersionUID = 8890481402065068304L;
    Logger logger = Logger.getLogger(LoginAction.class.getName());
    private User usuari = new User();
    private Map<String, Object> session;
    private List<Label> listEtiquetes;
    UsersService usuariService;
    SubscriptionsService subscripcioService;

    private String newPassword;
    private String retypePassword;
    
    private String errorMessage;
    
    private File picture;
    

    public File getPicture() {
		return picture;
	}

	public void setPicture(File picture) {
		this.picture = picture;
	}

    public LoginAction(UsersService usuariService, SubscriptionsService subscripcioService) {
        this.usuariService = usuariService;
        this.subscripcioService = subscripcioService;
    }

    public Object getModel() {
        return usuari;
    }

    public Map<String, Object> getSession() {
        return session;
    }

    public void setSession(Map<String, Object> arg0) {
        session = arg0;
    }

    public String initPage() {

        return SUCCESS;
    }

    public String login() {

        //Autenticacio usuari amb login i password contra la BD
        try {

        	session = ActionContext.getContext().getSession();
        	
	        if ("".equals(usuari.getLogin()) || "".equals(Utils.digestMD5(usuari.getPassword()))) {
	            addActionError("Login cannot be empty");
	            return INPUT;
	        }

	        User usuariAut = usuariService.login(usuari.getLogin(), Utils.digestMD5(usuari.getPassword()));
            session.put(Constants.SESSIO_USUARI_AUTENTICAT, usuariAut);
            return SUCCESS;

        } catch (Exception e){
                e.printStackTrace();
            addActionError("Authentication failed");
            return INPUT;
        }

    }

    public String logout() {

        session = ActionContext.getContext().getSession();

        session.remove(Constants.SESSIO_USUARI_AUTENTICAT);
        return SUCCESS;


    }

    public String registreUsuari() {
    	
    	if("".equals(usuari.getLogin().trim()) && "".equals(usuari.getPassword().trim())) 
    		addActionError("Both login and password are required");
    	else if ("".equals(usuari.getLogin().trim())) 
    		addActionError("Login required");
    	else if ("".equals(usuari.getPassword().trim())) 
    		addActionError("Password required");
        else if ("".equals(getRetypePassword().trim())) 
        	addActionError("Must retype password");
        else if (!usuari.getPassword().trim().equals(getRetypePassword().trim())) 
        	addActionError("Passwords don't match");
        else {	       
	        try {
	        	
	        	if(!usuariService.existsLogin(usuari.getLogin())) {
		        	//Hash password with MD5
		        	usuari.setPassword(Utils.digestMD5(usuari.getPassword()));
		        	//Save user
	        		usuariService.addUser(usuari);
	        		//Save picture
	        		if (picture!=null)
		        		savePictureFile(usuari.getLogin());
		
	        	} else 
	                addActionError("Login " + usuari.getLogin() + " already exists. Try another one.");
	        	
	        	
	        } catch (Exception e) {
                addActionError("Some kind of error has ocurred. Try again later.");
	        }    
        }
        if (getActionErrors().size()>0)	
        	return INPUT;
        else {
        	session.put(Constants.SESSIO_USUARI_AUTENTICAT, usuari);
            return SUCCESS;
        }

    }
    
    private void savePictureFile(String fileName) {
		try {
			FileInputStream fileInput = new FileInputStream(picture);
			BufferedInputStream bufferedInput = new BufferedInputStream(fileInput);
			String path = ServletActionContext.getServletContext().getRealPath("img/users");
			FileOutputStream fileOutput = new FileOutputStream (new File(path+"/"+fileName+".jpg"));
			BufferedOutputStream bufferedOutput = new BufferedOutputStream(fileOutput);
			
			byte [] array = new byte[1000];
			int leidos = bufferedInput.read(array);
			while (leidos > 0)
			{
				bufferedOutput.write(array,0,leidos);
				leidos=bufferedInput.read(array);
			}

			bufferedInput.close();
			bufferedOutput.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

    public String editarUsuari() throws Exception {
    	
    	if ("".equals(usuari.getLogin().trim())) 
    		addActionError("Login required");
    	else if (!"".equals(usuari.getPassword().trim()) && "".equals(getRetypePassword().trim())) 
        	addActionError("Must retype password");
        else if (!"".equals(usuari.getPassword().trim()) && !getNewPassword().trim().equals(getRetypePassword().trim())) 
        	addActionError("Passwords don't match");
        else {	       
            try {
        		//Hash password with MD5 if not empty
            	if (!"".equals(usuari.getPassword().trim()))
            		usuari.setPassword(Utils.digestMD5(getNewPassword()));
	        	//Update user
        		usuariService.updateUser(usuari);
        		//Save/change picture
        		if (picture!=null)
	        		savePictureFile(usuari.getLogin());
        		
            } catch (Exception e) {
            	e.printStackTrace();
                addActionError("Some kind of error has ocurred. Try again later.");
	        }    
        }
        if (getActionErrors().size()>0)	
        	return INPUT;
        else {
        	session.put(Constants.SESSIO_USUARI_AUTENTICAT, usuari);
            return SUCCESS;
        }
    }
    
    
    

    public void setListEtiquetes(List<Label> listEtiquetes) {
        this.listEtiquetes = listEtiquetes;
    }

    public List<Label> getListEtiquetes() {
        return listEtiquetes;
    }

	public User getUsuari() {
		return usuari;
	}

	public void setUsuari(User usuari) {
		this.usuari = usuari;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public String getRetypePassword() {
		return retypePassword;
	}

	public void setRetypePassword(String retypePassword) {
		this.retypePassword = retypePassword;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}
    
}
